package com.smart.wap.service;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.DatePattern;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.util.ObjUtil;
import cn.hutool.core.util.RandomUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.crypto.digest.DigestUtil;
import cn.hutool.http.HttpRequest;
import cn.hutool.http.HttpResponse;
import cn.hutool.json.JSON;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson2.JSONObject;
import com.smart.common.cache.CacheService;
import com.smart.common.entities.constant.SocKetTips;
import com.smart.common.entities.core.Page;
import com.smart.manager.member.entities.enums.PigPlanStatus;
import com.smart.manager.member.entities.enums.PigPlanTime;
import com.smart.manager.member.entities.models.MemberMaterialPig;
import com.smart.manager.member.entities.models.MemberMaterialPigPlan;
import com.smart.manager.member.entities.models.query.QMemberMaterialPig;
import com.smart.manager.member.entities.models.query.QMemberMaterialPigPlan;
import com.smart.manager.member.entities.views.MemberPigView;
import com.smart.manager.member.entities.views.query.QMemberPigView;
import com.smart.manager.member.repository.MemberMaterialPigPlanRepository;
import com.smart.manager.pop.repository.ActivityAttendRepository;
import com.smart.manager.product.entities.enums.CameraDirection;
import com.smart.manager.product.entities.enums.PigStatus;
import com.smart.manager.product.entities.enums.RfidStatus;
import com.smart.manager.product.entities.enums.RfidUseStatus;
import com.smart.manager.product.entities.models.BasicCameraDetail;
import com.smart.manager.product.entities.models.BasicRfid;
import com.smart.manager.product.entities.models.PigLevel;
import com.smart.manager.product.entities.models.PropsCombo;
import com.smart.manager.product.entities.models.query.QBasicCameraDetail;
import com.smart.manager.product.entities.models.query.QBasicRfid;
import com.smart.manager.product.entities.models.query.QPigLevel;
import com.smart.manager.product.entities.models.query.QPropsCombo;
import com.smart.manager.product.entities.views.BasicRfidView;
import com.smart.manager.product.entities.views.PigLevelView;
import com.smart.manager.product.repository.BasicCameraDetailRepository;
import com.smart.manager.system.repository.ConfigRepository;
import com.smart.manager.work.entities.assembler.StaffSimple;
import com.smart.manager.work.entities.assembler.WorkOrder;
import com.smart.manager.work.entities.enums.PigOrderKind;
import com.smart.manager.work.entities.enums.PigOrderStatus;
import com.smart.manager.work.entities.enums.StaffStatus;
import com.smart.manager.work.entities.models.BasicStaff;
import com.smart.manager.work.entities.models.PigOrder;
import com.smart.manager.work.entities.models.PigOrderFoods;
import com.smart.manager.work.entities.models.query.QBasicStaff;
import com.smart.manager.work.entities.models.query.QPigOrder;
import com.smart.manager.work.entities.models.query.QPigOrderFoods;
import com.smart.manager.work.views.BasicStaffView;
import com.smart.manager.work.views.query.QBasicStaffView;
import com.smart.service.remind.RemindService;
import com.smart.service.socket.WebSocket;
import com.smart.utils.WorkAcl;
import com.smart.wap.bodys.RWorkBody;
import com.smart.wap.bodys.WorkOrderResult;
import com.smart.wap.bodys.WorkStaffBody;
import io.ebean.annotation.Transactional;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.jetbrains.annotations.NotNull;
import org.springframework.stereotype.Service;

import javax.validation.ConstraintViolation;
import javax.validation.Validation;
import javax.validation.ValidatorFactory;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.util.*;
import java.util.stream.Collectors;

@Service
@RequiredArgsConstructor
@Slf4j
public class WorkStaffService {


    private final RemindService remindservice;
    private final BasicCameraDetailRepository basicCameraDetailRepository;
    private final CacheService cacheService;
    private final WebSocket webSocket;
    private final MemberMaterialPigPlanRepository materialPigPlanRepository;
    private final ConfigRepository configRepository;

    private final ActivityAttendRepository activityAttendRepository;


    /**
     * 终止任务
     */
    private final static String STOP = "https://open.ys7.com/api/v3/open/cloud/video/frame/stop";
    /**
     * 开始任务
     */
    private final static String START = "https://open.ys7.com/api/open/cloud/v1/instant/record/save";

    /**
     * 开始任务
     */
    private final static String PLAYBACK = "https://open.ys7.com/api/open/cloud/v1/rec/video/save";

    /**
     * 获取个人信息
     *
     * @param id id
     * @return {@link StaffSimple}
     */
    public StaffSimple getInfo(Long id) {
        BasicStaff staff = new QBasicStaff().id.eq(id).setMaxRows(1).findOne();
        return BeanUtil.copyProperties(staff, StaffSimple.class);
    }

    /**
     * 获取个人信息
     *
     * @param id id
     * @return {@link StaffSimple}
     */
    public String getConfig(Long id) {
        String object = (String) configRepository.readCache("WeixinMa").get("openAvatar");
        return object;
    }

    /**
     * 获取个人信息
     *
     * @param id id
     * @return {@link StaffSimple}
     */
    public List<BasicStaffView> getInfoList(Long id) {
        int count = new QBasicStaff().id.eq(id).isManage.eq(true).setMaxRows(1).findCount();
        Assert.isTrue(count > 0, "您的权限不够!");
        return new QBasicStaffView().findList();
    }

    /**
     * 创建账号
     *
     * @param id   管理id
     * @param body body
     */
    public void setAccount(Long id, WorkStaffBody.NewBody body) {

        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(orEmpty.isEmpty(), "账号异常!");
        Assert.isTrue(orEmpty.get().getStatus().equals(StaffStatus.NORMAL), "账号已经被禁用!");
        Assert.isTrue(orEmpty.get().getIsManage(), "没有权限!");
        BasicStaff staff = orEmpty.get();
        String datetime = String.format("YG%s", RandomUtil.randomNumbers(6));
        int count = new QBasicStaff().phone.eq(body.getPhone()).findCount();
        Assert.isFalse(count > 0, "手机号已被占用!");
        BasicStaff freshStaff = new BasicStaff().setAvatar(body.getAvatar()).setSite(staff.getSite()).setIsManage(false).setStatus(StaffStatus.NORMAL).setCode(datetime);
        BeanUtil.copyProperties(body, freshStaff);
        freshStaff.setPassword(DigestUtil.bcrypt("123456")).insert();

    }

    /**
     * 查询自己的工单
     *
     * @return {@link List}<{@link PigOrder}>
     */
    public Page<PigOrder> getOneWorkOder(RWorkBody.SearchBody search) {
        Long id = WorkAcl.getLoginId();
        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        if (orEmpty.isEmpty()) {
            return null;
        }
        QPigOrder query = new QPigOrder();
        query.status.ne(PigOrderStatus.COMPLETED).kind.eq(search.getKind()).staff.code.eq(orEmpty.get().getCode());
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        Page<PigOrder> load = new Page<PigOrder>().load(query.findPagedList());
        load.getRecords().forEach(x -> {
            if (search.getKind().equals(PigOrderKind.L1)) {
                return;
            }
            List<String> cameraCode = x.getPig().getPigsty().getCameraCode();
            List<BasicCameraDetail> details = new QBasicCameraDetail().passageId.in(cameraCode).findList();
            CollUtil.sort(details, Comparator.comparing(BasicCameraDetail::getCameraDirection, (direction1, direction2) -> {
                if (direction1.equals(CameraDirection.FORMER)) {
                    return -1; // 如果direction1等于"前摄像头"，则排在前面
                } else if (direction2.equals(CameraDirection.FORMER)) {
                    return 1; // 如果direction2等于"前摄像头"，则排在前面
                } else {
                    return 0; // 其他情况不变
                }
            }));
            ArrayList<String> cameraUrl = new ArrayList<>();
            details.forEach(c -> {
                cameraUrl.add(basicCameraDetailRepository.getLive(c));
            });
            x.setCameraUrl(cameraUrl);
        });
        return load;
    }


    /**
     * 查询自己的工单
     *
     * @return {@link List}<{@link PigOrder}>
     */
    public Page<PigOrderFoods> getOneWorkOderFoods(RWorkBody.SearchBody search) {
        Long id = WorkAcl.getLoginId();
        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        if (orEmpty.isEmpty()) {
            return null;
        }
        QPigOrderFoods query = new QPigOrderFoods();
        query.status.ne(PigOrderStatus.COMPLETED).kind.eq(PigOrderKind.L3).staff.code.eq(orEmpty.get().getCode());
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        Page<PigOrderFoods> load = new Page<PigOrderFoods>().load(query.findPagedList());
        load.getRecords().forEach(x -> {
            List<String> cameraCode = x.getPigsty().getCameraCode();
            List<BasicCameraDetail> details = new QBasicCameraDetail().passageId.in(cameraCode).findList();
            CollUtil.sort(details, Comparator.comparing(BasicCameraDetail::getCameraDirection, (direction1, direction2) -> {
                if (direction1.equals(CameraDirection.FORMER)) {
                    return -1; // 如果direction1等于"前摄像头"，则排在前面
                } else if (direction2.equals(CameraDirection.FORMER)) {
                    return 1; // 如果direction2等于"前摄像头"，则排在前面
                } else {
                    return 0; // 其他情况不变
                }
            }));
            ArrayList<String> cameraUrl = new ArrayList<>();
            details.forEach(c -> {
                cameraUrl.add(basicCameraDetailRepository.getLive(c));
            });
            List<MemberPigView> list = new QMemberPigView().code.in(x.getPigCodeList()).findList();
            x.setPigDetail(list);
            x.setCameraUrl(cameraUrl);
        });
        return load;
    }


    public Page<PigOrder> getOderList(Long id, PigOrderKind status, PigOrderStatus orderStatus, RWorkBody.SearchAllBody search) {
        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        if (orEmpty.isEmpty()) {
            return null;
        }
        BasicStaff staff = orEmpty.get();
        QPigOrder query = new QPigOrder().status.eq(orderStatus).kind.eq(status).staff.code.eq(staff.getCode());
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<PigOrder>().load(query.findPagedList());
    }

    public Page<PigOrderFoods> getFoodOder(Long id, PigOrderStatus orderStatus, RWorkBody.SearchAllBody search) {
        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        if (orEmpty.isEmpty()) {
            return null;
        }
        BasicStaff staff = orEmpty.get();
        QPigOrderFoods query = new QPigOrderFoods().status.eq(orderStatus).kind.eq(PigOrderKind.L3).staff.code.eq(staff.getCode());
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        Page<PigOrderFoods> load = new Page<PigOrderFoods>().load(query.findPagedList());
        load.getRecords().forEach(x->{
            List<MemberPigView> list = new QMemberPigView().code.in(x.getPigCodeList()).findList();
            x.setPigDetail(list);
        });
        return load;
    }


    /**
     * 查询所有工单
     *
     * @param id 请求id
     * @return {@link List}<{@link PigOrder}>
     */
    public Page<PigOrder> getListWorkOrder(Long id, RWorkBody.SearchAllBody search) {

        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        Assert.isTrue(orEmpty.isPresent(), "查询账号异常");
        Assert.isTrue(orEmpty.get().getIsManage(), "权限不足!");
        QPigOrder query = new QPigOrder().status.eq(PigOrderStatus.ALLOCATED).kind.eq(PigOrderKind.L1);
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<PigOrder>().load(query.findPagedList());
    }

    /**
     * 查询所有工单
     *
     * @param id 请求id
     * @return {@link List}<{@link PigOrder}>
     */
    public Page<PigOrder> getWorkOrder(Long id, WorkStaffBody.Search search) {
        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        Assert.isTrue(orEmpty.isPresent(), "查询账号异常");
        Assert.isTrue(orEmpty.get().getIsManage(), "权限不足!");
        QPigOrder query = new QPigOrder().status.eq(search.getStatus()).kind.eq(search.getKind());
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<PigOrder>().load(query.findPagedList());
    }

    /**
     * 查询所有工单
     *
     * @param id 请求id
     * @return {@link List}<{@link PigOrder}>
     */
    public Page<PigOrder> getList(Long id, PigOrderKind kind, RWorkBody.SearchAllBody search) {

        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        if (orEmpty.isEmpty()) {
            return null;
        }
        BasicStaff staff = orEmpty.get();
        QPigOrder query = new QPigOrder().staff.code.eq(staff.getCode()).status.eq(PigOrderStatus.COMPLETED).kind.eq(kind);
        query.setFirstRow(search.firstRow()).setMaxRows(search.maxRows());
        return new Page<PigOrder>().load(query.findPagedList());
    }


    /**
     * 派发工单
     *
     * @param id   管理id
     * @param body body
     */
    @Transactional(rollbackFor = Exception.class)
    public void distribute(Long id, WorkStaffBody.distributeBody body) {
        Optional<BasicStaff> staff = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        staff.ifPresent(x -> {
            Assert.isTrue(x.getIsManage(), "权限不够");
            Optional<PigOrder> order = new QPigOrder().code.eq(body.getCode()).setMaxRows(1).findOneOrEmpty();
            Assert.isFalse(order.isEmpty(), "派发的订单不存在");
            Optional<BasicStaff> orEmpty = new QBasicStaff().code.eq(body.getStaffCode()).setMaxRows(1).findOneOrEmpty();
            Assert.isFalse(orEmpty.isEmpty(), "派发的账号不存在");
            Assert.isTrue(orEmpty.get().getStatus().equals(StaffStatus.NORMAL), "派发的账号状态不正确");
            order.get().setStaff(new BasicStaffView().setCode(body.getStaffCode())).setStatus(PigOrderStatus.PROGRESS).update();

            Optional<MemberMaterialPig> pig = new QMemberMaterialPig().id.eq(order.get().getPig().getId()).setMaxRows(1).findOneOrEmpty();
            pig.ifPresent(c -> c.setStaff(new BasicStaffView().setCode(x.getCode())).update());
            if (!body.getStaffCode().equals(x.getCode())) {
                String openId = new QBasicStaff().code.eq(body.getStaffCode()).setMaxRows(1).select(QBasicStaff.Alias.openId).findSingleAttribute();
                if (StrUtil.isNotBlank(openId)) {
                    String content = String.format("%s%s天%s猪", pig.get().getBreed().getName(), pig.get().getPigLevel().getDay(), pig.get().getPigLevel().getKind().getLabel());
                    remindservice.sendMiniProgramsMsg(openId, content, "您有新的猪猪入栏工单,请及时查看", false);
                }
                //如果是 派发给自己 则不通知
            }
        });

    }

    /**
     * 开始录像
     *
     * @param code 工单code
     */
    public void videoTape(Long id, String code) {

        List<BasicCameraDetail> details = null;
        PigOrderFoods orderFoods = null;
        PigOrder order = new QPigOrder().code.eq(code).setMaxRows(1).findOne();
        if (ObjUtil.isNotNull(order)) {
            MemberMaterialPig one = new QMemberMaterialPig().id.eq(order.getPig().getId()).findOne();
            Assert.notNull(one, "猪仔不存在!");
            details = new QBasicCameraDetail().passageId.in(one.getPigsty().getCameraCode()).findList();
        } else {
            orderFoods = new QPigOrderFoods().code.eq(code).setMaxRows(1).findOne();
            if (ObjUtil.isNotNull(orderFoods)) {
                details = new QBasicCameraDetail().passageId.in(orderFoods.getPigsty().getCameraCode()).findList();
            }
        }
        String accessToken = cacheService.getCameraTokenCache().get("accessToken");
        Map<String, Object> map = Map.of("projectId", 123456789, "recordSeconds", 360, "retryNum", 2, "streamType", 1);
        CollUtil.sort(details, Comparator.comparing(BasicCameraDetail::getCameraDirection, (direction1, direction2) -> {
            if (direction1.equals(CameraDirection.FORMER)) {
                return -1; // 如果direction1等于"前摄像头"，则排在前面
            } else if (direction2.equals(CameraDirection.FORMER)) {
                return 1; // 如果direction2等于"前摄像头"，则排在前面
            } else {
                return 0; // 其他情况不变
            }
        }));
        Assert.isFalse(CollUtil.isEmpty(details), "当前猪圈暂未绑定摄像头!");
        HttpResponse execute = HttpRequest.post(START)
                .header("accessToken", accessToken)
                .header("deviceSerial", details.get(0).getDeviceSerial())
                .header("localIndex", details.get(0).getChannelNo().toString())
                .form(map).execute();
        //请求录制
        JSON parse = JSONUtil.parse(execute.body());
        Assert.isTrue(parse.getByPath("meta.code").equals(200), (String) parse.getByPath("meta.message"));
        String task = parse.getByPath("data.taskId").toString();
        log.warn("任务 id = {}", task);
        cacheService.getDumpCache().put(task, code);
        cacheService.getDumpCache().put(code, task);
        if (ObjUtil.isNotNull(order)) {
            order.setVideo("http://admin.leoweb.cloud:40033/f/w0ty/shangchuan.mp4").setTaskId(task).update();
        } else if (ObjUtil.isNotNull(orderFoods)){
            orderFoods.setVideo("http://admin.leoweb.cloud:40033/f/w0ty/shangchuan.mp4").setTaskId(task).update();
        }
}


    /**
     * @param code
     * @param beginTime
     * @param outTime   //备选方案
     */
    public void getTheReplay(String code, String beginTime, String outTime) {
        Optional<PigOrder> order = new QPigOrder().code.eq(code).setMaxRows(1).findOneOrEmpty();
        List<BasicCameraDetail> details = null;
        if (order.isPresent()) {
            MemberMaterialPig one = new QMemberMaterialPig().id.eq(order.get().getId()).findOne();
            Assert.notNull(one, "猪仔不存在!");
            details = new QBasicCameraDetail().passageId.in(one.getPigsty().getCameraCode()).findList();
        } else {
            Optional<PigOrderFoods> orderFoods = new QPigOrderFoods().code.eq(code).setMaxRows(1).findOneOrEmpty();
            if (orderFoods.isPresent()) {
                details = new QBasicCameraDetail().passageId.in(orderFoods.get().getPigsty().getCameraCode()).findList();
            }
        }

        if (ObjUtil.isNotNull(details)) {
            String accessToken = cacheService.getCameraTokenCache().get("accessToken");
            Map<String, Object> map = Map.of("projectId", 123456789, "startTime", beginTime, "endTime", outTime, "recType", "local");
            CollUtil.sort(details, Comparator.comparing(BasicCameraDetail::getCameraDirection, (direction1, direction2) -> {
                if (direction1.equals(CameraDirection.FORMER)) {
                    return -1; // 如果direction1等于"前摄像头"，则排在前面
                } else if (direction2.equals(CameraDirection.FORMER)) {
                    return 1; // 如果direction2等于"前摄像头"，则排在前面
                } else {
                    return 0; // 其他情况不变
                }
            }));
            Assert.isFalse(CollUtil.isEmpty(details), "当前猪圈暂未绑定摄像头!");
            HttpResponse execute = HttpRequest.post(PLAYBACK)
                    .header("accessToken", accessToken)
                    .header("Content-Type", "application/x-www-form-urlencoded")
                    .header("deviceSerial", details.get(0).getDeviceSerial())
                    .header("localIndex", details.get(0).getChannelNo().toString())
                    .form(map).execute();
            //请求录制
            JSON parse = JSONUtil.parse(execute.body());
            log.warn("parse = {}", parse);
            Assert.isTrue(parse.getByPath("meta.code").equals(200), (String) parse.getByPath("meta.message"));
            String task = parse.getByPath("data.taskId").toString();
            cacheService.getDumpCache().put(task, code);
        }
    }


    /**
     * 停止任务
     */
    public void stop(String code) {
//        Optional<PigOrder> order = new QPigOrder().code.eq(code).setMaxRows(1).findOneOrEmpty();
//        order.ifPresent(x -> {
//            Assert.isFalse(StrUtil.isBlank(order.get().getTaskId()), "当前工单暂无 暂停任务");
//            String accessToken = cacheService.getCameraTokenCache().get("accessToken");
//            Map<String, Object> map = Map.of("accessToken", accessToken,"taskId", order.get().getTaskId());
//            HttpResponse execute = HttpRequest.post(STOP)
//                    .form(map)
//                    .execute();
//            log.warn("execute.body() === {}", execute.body());
//            JSON parse = JSONUtil.parse(execute.body());
//            Assert.isTrue(parse.getByPath("meta.code").equals(200), (String) parse.getByPath("meta.message"));
//        });


        String taskId = cacheService.getDumpCache().get(code);
        log.warn("找的taskId是 {} == {}", taskId, code);
        Assert.isFalse(StrUtil.isBlank(taskId), "当前工单暂无 暂停任务");
        String accessToken = cacheService.getCameraTokenCache().get("accessToken");
        HttpResponse execute = HttpRequest.post(STOP)
                .header("Content-Type", "application/x-www-form-urlencoded")
                .body("accessToken=" + accessToken + "&taskId=" + taskId)
                .execute();
        log.warn("execute.body() === {}", execute.body());
        JSON parse = JSONUtil.parse(execute.body());
        Assert.isTrue(parse.getByPath("meta.code").equals(200), (String) parse.getByPath("meta.message"));
        cacheService.getDumpCache().remove(code);
    }

    /**
     * 验证表单是否填写
     *
     * @param obj 验证的对象
     */
    public void verification(Object obj) {
        ValidatorFactory factory = Validation.buildDefaultValidatorFactory();
        Set<ConstraintViolation<Object>> validate = factory.getValidator().validate(obj);
        Assert.isTrue(validate.isEmpty(), validate.stream().map(ConstraintViolation::getMessage).collect(Collectors.toList()).toString());
    }


    /**
     * 入圈工单处理
     *
     * @param body body
     */
    @Transactional(rollbackFor = Exception.class)
    public void enterTheCircle(Long id, WorkStaffBody.addBody body) {
        log.warn("入圈工单处理 :{}", body);
        WorkOrder.EnterTheCircleBody order = body.getContent();
        //验证 表单是否正确
//        verification(order);
        Assert.notNull(order, "入圈工单 表单异常!");
        Optional<PigOrder> empty = new QPigOrder().code.eq(body.getCode()).setMaxRows(1).findOneOrEmpty();
        empty.ifPresent(x -> {
            //判断天数不能小于购买天数
            Optional<BasicStaff> staff = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
            Assert.isFalse(staff.isEmpty(), "不存在的饲养员请联系管理员!");
            BasicStaff basicStaff = staff.get();
            //判断是否存在该耳标
            int count = new QBasicRfid().beaconMac.eq(body.getContent().getRfid()).findCount();
            Assert.isFalse(count > 0, "该耳标已存在 请勿重复入栏");
            //创建耳标
            new BasicRfid().setBeaconMac(body.getContent().getRfid()).setStatus(RfidStatus.AWAIT).setUseStatus(RfidUseStatus.USING).insert();
            //处理 工单数据
            x.setStatus(PigOrderStatus.COMPLETED).setCompleteTime(LocalDateTime.now()).setContent(order).update();
            //处理 更新玩家猪猪数据
            MemberMaterialPig pig = new QMemberMaterialPig().id.eq(order.getId()).setMaxRows(1).findOne();
            Assert.isFalse(ObjUtil.isNull(pig), "处理的猪猪不存在");
            addFood(pig);
            Optional<PigLevel> pigLevel = new QPigLevel().day.eq(body.getContent().getDay()).breed.eq(pig.getBreed()).kind.eq(pig.getPigLevel().getKind()).findOneOrEmpty();
            Assert.isFalse(pigLevel.isEmpty(), "当前品种猪仔天数等级配置不存在请联系管理员添加!");
            pig.setStaff(new BasicStaffView().setCode(basicStaff.getCode()))
                    .setRfid(new BasicRfidView().setBeaconMac(order.getRfid()))
                    .setPigsty(body.getContent().getPigsty())
                    .setPigLevel(new PigLevelView().setId(pigLevel.get().getId()));
            //判断猪圈里面有没有猪了 , 如果有猪 将管理员转移到老的
            List<MemberPigView> list = new QMemberPigView().pigsty.eq(body.getContent().getPigsty()).findList();
            if (list.size() > 0) {
                pig.setPigsty(list.get(0).getPigsty());
            }
            pig.setStatus(PigStatus.NORMAL).update();

            activityAttendRepository.setPigSharePoster(pig.getCode(), pig.getMember().getId());
            //发送提示消息
            remindservice.sendEnterTheCircleMsg(pig.getMember().getId(), pig);
            //发送站内消息
            remindservice.sendInsideEnterTheCircleMsg(pig.getMember().getId(), pig);
            //发送 socket 消息
            webSocket.sendOneMessage(pig.getMember().getId(), SocKetTips.updatePigEnter);
        });

    }


    public void addPackage(MemberMaterialPig pig) {
        PropsCombo combo = new QPropsCombo().setMaxRows(1).findOne();
        Assert.isFalse(ObjUtil.isEmpty(combo), "入栏失败, 当前等级猪仔没有对应的低保套餐!");
        List<MemberMaterialPigPlan> pigPlans = new QMemberMaterialPigPlan().status.eq(PigPlanStatus.L1).eatDate.eq(LocalDate.now()).findList();
        ArrayList<PigPlanTime> times = new ArrayList<>();
        long breakfast = pigPlans.stream().filter(x -> x.getEatTime().equals(PigPlanTime.L1)).count();
        if (breakfast == 0) {
            times.add(PigPlanTime.L1);
        }
        long lunch = pigPlans.stream().filter(x -> x.getEatTime().equals(PigPlanTime.L2)).count();
        if (lunch == 0) {
            times.add(PigPlanTime.L2);
        }
        long dinner = pigPlans.stream().filter(x -> x.getEatTime().equals(PigPlanTime.L3)).count();
        if (dinner == 0) {
            times.add(PigPlanTime.L3);
        }
        materialPigPlanRepository.add(pig, combo, LocalDate.now(), times);
    }

    public void addFood(MemberMaterialPig pig){
        ArrayList<PigPlanTime> times = new ArrayList<>();
        PropsCombo combo = new QPropsCombo().isOrganic.eq(pig.getBreed().getIsOrganic()).isPack.eq(true).setMaxRows(1).findOne();
        Assert.isFalse(ObjUtil.isEmpty(combo), "入栏失败, 当前猪仔没有套餐包请联系管理员添加!");
        JSONObject feeding = configRepository.readCache("Feeding");
        String morning = feeding.getString("morning").concat(":00");
        String midday = feeding.getString("midday").concat(":00");
        String night = feeding.getString("night").concat(":00");
        LocalTime now = LocalTime.now(); // 现在
        LocalTime parseMorning = LocalTime.parse(morning);  //早上时间
        LocalTime parseMidday = LocalTime.parse(midday);   //中午时间
        LocalTime parseNight = LocalTime.parse(night);     //下午时间
        if (now.isBefore(parseMorning)) {
            times.add(PigPlanTime.L1);
        }
        if (now.isBefore(parseMidday)) {
            times.add(PigPlanTime.L2);
        }
        if (now.isBefore(parseNight)) {
            times.add(PigPlanTime.L3);
        }
        materialPigPlanRepository.add(pig, combo, LocalDate.now(), times);
    }

    /**
     * 角标
     *
     * @param id gl
     * @return {@link WorkOrderResult}
     */
    public WorkOrderResult getWorkOrderHorn(Long id) {
        Optional<BasicStaff> orEmpty = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(orEmpty.isEmpty(), "账号异常!");
        BasicStaff staff = orEmpty.get();
        WorkOrderResult result = new WorkOrderResult();
        List<PigOrderKind> orders = new QPigOrder().staff.code.eq(staff.getCode()).status.eq(PigOrderStatus.PROGRESS).order().id.desc().setMaxRows(300).select(QPigOrder.Alias.kind).findSingleAttributeList();
        int count1 = new QPigOrderFoods().staff.code.eq(staff.getCode()).status.eq(PigOrderStatus.PROGRESS).order().id.desc().setMaxRows(300).findCount();
        result.setFeeding(count1);
        for (PigOrderKind order : orders) {
            switch (order) {
                case L1:
                    result.setEnter(result.getEnter() + 1);
                    break;
                case L2:
                    result.setComeOut(result.getComeOut() + 1);
                    break;
                case L5:
                    result.setService(result.getService() + 1);
                    break;
            }
        }
        int pigCount = new QMemberMaterialPig().staff.code.eq(staff.getCode()).findCount();
        int count = 0;
        if (staff.getIsManage()) {
            count = new QPigOrder().status.eq(PigOrderStatus.ALLOCATED).findCount();
        }
        return result.setOneManage(pigCount).setAssign(count);
    }

    /**
     * 喂养工单处理
     */
    public void raise(Long id, WorkOrder.SubmitBody body) {
        Optional<PigOrderFoods> pigOrder = new QPigOrderFoods().id.eq(body.getId()).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(pigOrder.isEmpty(), "工单不存在!");
        PigOrderFoods order = pigOrder.get();
        order.setStatus(PigOrderStatus.COMPLETED).setCompleteTime(LocalDateTime.now()).update();
    }

    /**
     * 治疗工单处理
     *
     * @param body body
     */
    public void treatment(Long id, WorkOrder.TreatmentBody body) {
        Optional<BasicStaff> staff = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        staff.ifPresent(x -> {
            String datetime = String.format("GD%s%s", DateUtil.format(DateUtil.date(), DatePattern.PURE_DATETIME_PATTERN), RandomUtil.randomNumbers(3));
            new PigOrder().setPig(new MemberPigView()
                            .setId(body.getPigId()))
                    .setStaff(new BasicStaffView().setCode(x.getCode()))
                    .setContent(body.getContent())
                    .setKind(PigOrderKind.L4)
                    .setStatus(PigOrderStatus.COMPLETED)
                    .setCompleteTime(LocalDateTime.now())
                    .setCode(datetime).insert();
        });
    }


    /**
     * 出圈工单处理
     *
     * @param body body
     */
    public void outOfTheCircle(Long id, WorkStaffBody.addBody body) {
        log.warn("出圈工单处理 :{}", body.getCode());


    }

    /**
     * 服务工单处理
     *
     * @param body body
     */
    public void ministry(Long id, WorkOrder.SubmitBody body) {
        log.warn("服务工单处理 :{}", body.getId());
        Optional<PigOrder> pigOrder = new QPigOrder().id.eq(body.getId()).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(pigOrder.isEmpty(), "工单不存在!");
        PigOrder order = pigOrder.get();
        order.setStatus(PigOrderStatus.COMPLETED).setCompleteTime(LocalDateTime.now()).update();
    }


    public List<MemberMaterialPig> getOneList(Long id) {
        Optional<BasicStaff> staff = new QBasicStaff().id.eq(id).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(staff.isEmpty(), "饲养员不存在!");
        List<MemberMaterialPig> pigs = new QMemberMaterialPig().staff.code.eq(staff.get().getCode()).findList();
        for (MemberMaterialPig pig : pigs) {
            if (ObjUtil.isNotEmpty(pig.getPigsty())) {
                List<String> cameraCode = pig.getPigsty().getCameraCode();
                List<BasicCameraDetail> cameras = new QBasicCameraDetail().passageId.in(cameraCode).findList();
                ArrayList<String> strings = new ArrayList<>();
                for (BasicCameraDetail camera : cameras) {
                    String url = basicCameraDetailRepository.getLive(camera);
                    strings.add(url);
                }
                pig.setPigsty(pig.getPigsty().setCameraUrl(strings));
            }
        }
        return pigs;

    }

    public MemberMaterialPig getPig(String mac) {
        Optional<MemberMaterialPig> pig = new QMemberMaterialPig().rfid.beaconMac.eq(mac).setMaxRows(1).findOneOrEmpty();
        Assert.isFalse(pig.isEmpty(), "当前猪仔不存在, 请先入圈");
        return pig.get();

    }

    public void setImg(WorkStaffBody.SetInfo body) {
        WorkAcl.getLoginId();
        BasicStaff staff = new QBasicStaff().id.eq(WorkAcl.getLoginId()).setMaxRows(1).findOne();
        if (ObjUtil.isNotNull(staff)) {
            staff.setAvatar(body.getAvatarUrl()).update();
        }
    }


    public WorkOrderResult.Finish getDetailJob() {
        LocalDateTime start = LocalDateTime.parse(LocalDate.now().toString().concat(" ").concat("00:00:00"), DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
        LocalDateTime stop = LocalDateTime.parse(LocalDate.now().toString().concat(" ").concat("23:59:59"), DateTimeFormatter.ofPattern(DatePattern.NORM_DATETIME_PATTERN));
        List<PigOrder> pigOrders = new QPigOrder().staff.id.eq(WorkAcl.getLoginId()).status.in(PigOrderStatus.COMPLETED, PigOrderStatus.PROGRESS).createTime.between(start, stop).findList();
        List<PigOrderFoods> pigOrderFoods = new QPigOrderFoods().staff.id.eq(WorkAcl.getLoginId()).status.in(PigOrderStatus.COMPLETED, PigOrderStatus.PROGRESS).createTime.between(start, stop).findList();
        return getFinish(pigOrders,pigOrderFoods);
    }

    @NotNull
    private static WorkOrderResult.Finish getFinish(List<PigOrder> list,List<PigOrderFoods> pigOrderFoods) {
        WorkOrderResult.Finish finish = new WorkOrderResult.Finish();
        List<PigOrderKind> kinds = list.stream().map(PigOrder::getKind).collect(Collectors.toList());


        for (PigOrderKind pigOrderKind : kinds) {
            switch (pigOrderKind) {
                case L1:
                    finish.setEnter(finish.getEnter() + 1);
                    break;
                case L2:
                    finish.setOut(finish.getOut() + 1);
                    break;
                case L4:
                    finish.setSickness(finish.getSickness() + 1);
                    break;
                case L5:
                    finish.setServe(finish.getServe() + 1);
            }
        }
        finish.setFeed(pigOrderFoods.size());
        long count11 = pigOrderFoods.stream().filter(x -> x.getStatus().equals(PigOrderStatus.PROGRESS)).count();
        long count22 = pigOrderFoods.stream().filter(x -> x.getStatus().equals(PigOrderStatus.COMPLETED)).count();

        long count = list.stream().filter(x -> x.getStatus().equals(PigOrderStatus.PROGRESS)).count();
        long count1 = list.stream().filter(x -> x.getStatus().equals(PigOrderStatus.COMPLETED)).count();

        finish.setToBeContinued((int) (count+count11));
        finish.setTotal(list.size());
        finish.setCont((int) (count1+count22));
        return finish;
    }
}
